package com.suixun.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.suixun.enums.ShowEnum;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suixun.dao.CaseDisplayMapper;
import com.suixun.dao.redis.RedisDao;
import com.suixun.domain.CaseDisplay;
import com.suixun.exceptions.SuixunException;
import com.suixun.service.CaseDisplayService;
import com.suixun.utils.ListUtil;

/**
 * <p>
 * 案例展示 服务实现类
 * </p>
 *
 * @author jacky
 * @since 2018-01-11
 */
@Service
public class CaseDisplayServiceImpl extends ServiceImpl<CaseDisplayMapper, CaseDisplay> implements CaseDisplayService {

    @Resource
    private CaseDisplayMapper caseDisplayMapper;
    @Resource
    private RedisDao redisDao;

    @Override
    @Cacheable(value = "caseDisplayCache", key = "'caseDisplay_pageExclusionContent_' + #page + '_' + #size + '_' + #title + '_' + #isShow")
    public PageInfo<CaseDisplay> pageExclusionContent(int page, int size, String title, Integer isShow) {
        PageHelper.startPage(page, size);
        Map<String, Object> map = new HashMap<>();
        map.put("title", title);
        map.put("isShow", isShow);
        return new PageInfo<>(caseDisplayMapper.listExclusionContent(map));
    }

    @Override
    @Cacheable(value = "caseDisplayCache", key = "'caseDisplay_getById_' + #id")
    public CaseDisplay getById(Integer id) {
        return this.selectById(id);
    }

    @Override
    public void insert(CaseDisplay caseDisplay, Boolean isTop) {
        checkShow(caseDisplay.getIsShow());
        if (isTop != null && isTop) {
            caseDisplay.setTop(String.valueOf(new Date().getTime()));
        }
        this.insert(caseDisplay);

        redisDao.flushCaches("caseDisplay*");
    }

    private void checkShow(Integer show) {
        if (show != null && !ShowEnum.containType(show)) {
            throw new SuixunException("展示数据不符");
        }
    }

    @Override
    public void update(CaseDisplay caseDisplay, Boolean isTop) {
        checkShow(caseDisplay.getIsShow());
        if (caseDisplay.getId() == null) {
            throw new SuixunException("id不能为空");
        }
        Date date = new Date();
        if (isTop != null) {
            if (isTop) {
                caseDisplay.setTop(String.valueOf(date.getTime()));
            } else {
                caseDisplay.setTop("0");
            }
        }

        this.updateById(caseDisplay);

        redisDao.flushCaches("caseDisplay*");
    }

    @Override
    public void delete(String ids) {
        this.deleteBatchIds(ListUtil.Integers2List(ids));

        redisDao.flushCaches("caseDisplay*");
    }

}
